﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using NReader.Model;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Media.Imaging;

namespace Local.Service
{
    public class LocalFileService
    {
        public static async Task<BitmapImage> GetCover(int articleid)
        {
           await Utils.CheckFolder("cover");
            var folder = ApplicationData.Current.LocalFolder;
            try
            {
                StorageFile file = await folder.GetFileAsync(string.Format(@"cover\{0}.jpg", articleid));
                using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read))
                {
                    var bitmapImage = new BitmapImage();
                    bitmapImage.SetSource(stream);
                    return bitmapImage;
                }
            }
            catch (Exception)
            {
                return null;
                //throw;
            }
        }

        public static async Task<BitmapImage> SaveCover(int articleid, byte[] bytes)
        {
            var folder = ApplicationData.Current.LocalFolder;
            var file =
                await
                folder.CreateFileAsync(string.Format(@"cover\{0}.jpg", articleid),
                                       CreationCollisionOption.ReplaceExisting);
            await FileIO.WriteBytesAsync(file, bytes);
            using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read))
            {
                var bitmapImage = new BitmapImage();
                bitmapImage.SetSource(stream);
                return bitmapImage;
            }
        }

        public static async Task<bool> SaveChapterTxt(string webflag, int articleid, int chapterid, string content)
        {
            try
            {
                await Utils.CheckFolder("cache");
                await Utils.CheckFolder(string.Format(@"cache\{0}", articleid)); //cache\0
                await Utils.CheckFolder(string.Format(@"cache\{0}\{1}", articleid, webflag)); //cache\0\qidian
                var folder = ApplicationData.Current.LocalFolder;
                var subfolder = await folder.GetFolderAsync(string.Format(@"cache\{0}\{1}",articleid,webflag));
                var file =
                    await subfolder.CreateFileAsync(string.Format("{0}.txt",chapterid.ToString()), CreationCollisionOption.ReplaceExisting);
                await FileIO.WriteTextAsync(file, content);
                return true;
            }
            catch (Exception)
            {
                return false;
                //throw;
            }
        }

        public static async Task<string> GetChapterTxt(string webflag, int articleid, int chapterid)
        {
            try
            {
                var folder = ApplicationData.Current.LocalFolder;
                var subfolder = await folder.GetFolderAsync(string.Format(@"cache\{0}\{1}", articleid, webflag));
                var file =await subfolder.GetFileAsync(string.Format("{0}.txt", chapterid.ToString()));
                var result = await FileIO.ReadTextAsync(file);
                return result;
            }
            catch (Exception)
            {
                return string.Empty;
                //throw;
            }
        }

        /// <summary>
        /// 删除导入的文件
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static async Task<string> DeleteDocument(string filename)
        {
            try
            {
                var folder = ApplicationData.Current.LocalFolder;
                var subfolder = await folder.GetFolderAsync(@"document");
                var file = await subfolder.GetFileAsync(filename);
                await file.DeleteAsync();
                return string.Empty;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }


        /// <summary>
        /// 获取导入的文件内容
        /// </summary>
        /// <param name="filename">带后缀名的文件名</param>
        /// <param name="pos">读取的开始位置,比例0.01</param>
        /// <param name="len">需要读取的长度</param>
        /// <param name="encoding">文件编码</param>
        /// <param name="contentSize">文件大小</param>
        /// <returns></returns>
        public static async Task<FileDxInfo> GetDocumentContent(string filename, double pos, int len, string encoding)
        {
            FileDxInfo fileInfo=new FileDxInfo();
            try
            {
                var folder = ApplicationData.Current.LocalFolder;
                var subfolder = await folder.GetFolderAsync(@"document");
                var file = await subfolder.GetFileAsync(filename);
                IBuffer buffer = await FileIO.ReadBufferAsync(file);
                byte[] bytes = WindowsRuntimeBufferExtensions.ToArray(buffer, 0, (int) buffer.Length);
                fileInfo.FileSize = (int) buffer.Length;
                using (var stream = WindowsRuntimeBufferExtensions.AsStream(buffer))
                {
                    fileInfo.Content = Encoding.GetEncoding(encoding).GetString(bytes, 0, (int)buffer.Length);
                    //if (buffer.Length < len)
                    //    len = (int)buffer.Length;
                    //fileInfo.Content = Encoding.GetEncoding(encoding).GetString(bytes,
                    //                                                            int.Parse(
                    //                                                                Math.Round(buffer.Length * pos).
                    //                                                                    ToString()),
                    //                                                            len);
                    return fileInfo;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }

}
